<template>
  <div class="login">
    <div class="time_card">
      <span class="date">{{ now_date }}</span>
      <span>{{ now_time }}</span>
    </div>
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">工泰运营商平台</h3>
      <p class="sub_title">管理员登录</p>
      <div class="entrance" @click="changeQrLogin" v-if="login_mode == 'password'">
        <div class="bg_img"></div>
        <div class="tips">
          <div class="icon scan"></div>
          <div class="text">切换扫码登录</div>
        </div>
      </div>
      <div class="entrance" @click="changePassLogin" v-if="login_mode == 'qrcode'">
        <div class="bg_img pc"></div>
        <div class="tips">
          <div class="icon scan"></div>
          <div class="text">切换账号登录</div>
        </div>
      </div>
      <div v-if="login_mode == 'password'">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="账号">
            <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="密码"
            @keyup.enter="handleLogin">
            <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%"
            @keyup.enter="handleLogin">
            <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
        <el-form-item style="width:100%;">
          <el-button :loading="loading" size="large" type="primary" style="width:100%;" @click.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div style="float: right;" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </div>
      <div class="qrcode_cont" v-if="login_mode == 'qrcode'">
        <div class="auto_cont" v-if="!qrcode_error">
          <canvas id="canvasQrLogin" :width="280" :height="280"></canvas>
        </div>
        <div class="auto_cont" v-if="qrcode_error">
          <div class="scan_error"></div>
          <div class="error_tips">二维码已过期</div>
          <div class="error_refresh" @click="changeQrLogin">刷新</div>
        </div>
      </div>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2022-2023 All Rights Reserved. 版权所有：工泰电器有限公司
      </span>
      <a target="_blank" href="https://beian.miit.gov.cn" class="icp">浙ICP备09049222号-3
      </a>
    </div>
    <!-- <DialogQrLogin ref="dialogQr" /> -->
  </div>
</template>

<script setup>
import { qrlogin, getCodeImg } from "@/api/login";
import { getToken, setToken, removeToken } from '@/utils/auth'
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user'
import QRCode from "qrcode";
// import DialogQrLogin from "@/dialog/DialogQrLogin";


const userStore = useUserStore()
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: "",
});

const login_mode = ref("password")
const tinyCodeSrc = ref(null);
const tiny_str = ref(null);
const data = ref(null);
const timer = ref(null);
const qrcode_error = ref(true);

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);


const now_date = ref(undefined);
const now_day = ref(undefined);
const now_time = ref(undefined);
const now_timer = ref(undefined);

function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(() => {
        router.push({ path: redirect.value || "/" });
      }).catch(() => {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode();
        }
      });
    }
  });
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.data.img;
      loginForm.value.uuid = res.data.uuid;
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

function changeQrLogin() {
  login_mode.value = "qrcode"
  tinyCodeSrc.value = null;
  qrlogin().then((response) => {
    qrcode_error.value = false
    data.value = response.data.scanid
    createQr(response.data);
  })
}

function changePassLogin() {
  login_mode.value = "password"
  clearInterval(timer.value)
  timer.value = null
}

function checkLogin() {
  qrlogin({ scanid: data.value }).then((response) => {
    if (response.data.scan == 2) {
      setToken(response.data.token)
      clearInterval(timer.value)
      timer.value = null
      router.push({ path: "/" });
    } else if (response.data.scan == -1) {
      qrcode_error.value = true
      clearInterval(timer.value)
      timer.value = null
    }
  })
}

function createQr(row) {
  tiny_str.value =
    "https://opr.gtcharger.com?scanid=" + row.scanid;
  createTinyQrcode();
  timer.value = setInterval(() => {
    checkLogin(data.value)
  }, 1000)
}

function createTinyQrcode() {
  QRCode.toDataURL(tiny_str.value, { errorCorrectionLevel: "H" })
    .then((url) => {
      tinyCodeSrc.value = url.replace(/[\r\n]/g, "");
    })
    .catch((err) => {
      ElNotification({
        message: "二维码生成错误" + err,
        type: "error",
      });
      return;
    });
  setTimeout(() => {
    drawQrLogin();
  }, 100);
}

function drawQrLogin() {
  let canvas = document.getElementById("canvasQrLogin");
  let ctx = canvas.getContext("2d"); // 创建画布
  let img = new Image(); // 因为拿不到图片静态资源，所以创建图片标签
  img.setAttribute("crossOrigin", "anonymous"); // 解决图片跨域问题,也要放到赋值前，否贼大部分浏览器会报错
  img.src = tinyCodeSrc.value;
  // 加载图片
  img.onload = () => {
    // 绘制图片
    ctx.drawImage(img, 0, 0, 280, 280);
    // 合成图片
    let imgUrl = canvas.toDataURL("image/jpg");
    tinyCodeSrc.value = imgUrl;
  };
}

// 获取当前时间
function getTime() {
  let now = new Date();
  now_date.value = formatDate(now);
  now_day.value = now.getDay() % 2;
  now_time.value = formatTime(now);
}

// 格式化时间
function formatDate(date) {
  let year = date.getFullYear(); // 年
  let month = date.getMonth() + 1; // 月
  month = month < 10 ? "0" + month : month; // 如果只有一位，则前面补零
  let day = date.getDate(); // 日
  day = day < 10 ? "0" + day : day; // 如果只有一位，则前面补零
  let nowDate = `${year}-${month}-${day}`;
  return nowDate;
}

// 格式化时间
function formatTime(date) {
  let hour = date.getHours(); // 时
  hour = hour < 10 ? "0" + hour : hour; // 如果只有一位，则前面补零
  let minute = date.getMinutes(); // 分
  minute = minute < 10 ? "0" + minute : minute; // 如果只有一位，则前面补零
  let second = date.getSeconds(); // 秒
  second = second < 10 ? "0" + second : second; // 如果只有一位，则前面补零
  let nowDate = `${hour}:${minute}:${second}`;
  return nowDate;
}

console.log(
  "%c工泰运营商平台系统%cCopyright © 2022-2023 All Rights Reserved.\n%c温馨提示：请不要调皮地在此粘贴执行任何内容，这可能会导致您的账户受到攻击，给您带来损失 ！^_^\n%c生活变的再糟糕，也不妨碍我变得更好！欢迎加入工泰！",
  "font-size:36px;color:#1890ff;",
  "color:#eee;",
  "font-size:24px;color:#999;",
  ""
);

now_timer.value = setInterval(() => {
  getTime();
}, 1000);

getCode();
getCookie();
</script>

<style lang='scss' scoped>
.login {
  position: relative;
  // display: flex;
  // justify-content: center;
  // align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background2.jpg");
  background-size: cover;
}

.title {
  margin: 40px auto 10px auto;
  text-align: center;
  color: #707070;
}

.sub_title {
  margin: 0px auto 20px auto;
  text-align: center;
  color: #707070;
}

.time_card {
  position: absolute;
  color: #707070;
  top: 15%;
  left: 10%;
  text-align: center;
  cursor: pointer;
}

.time_card>span {
  display: block;
  margin: 5px 0;
}

.date {
  font-size: 24px;
}

.login-form {
  position: absolute;
  top: 30%;
  left: 5%;
  border-radius: 6px;
  background: #ffffff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.qrcode_cont {
  text-align: center;

  .auto_cont {
    position: relative;
    margin: 0 auto;
    width: 280px;
  }

  .scan_error {
    margin: 0 auto;
    width: 280px;
    height: 280px;
    background: #00000095;
  }

  .error_tips {
    position: absolute;
    left: calc(50% - 70px);
    top: calc(50% - 30px);
    font-size: 20px;
    color: #ffffff;
  }

  .error_refresh {
    margin: 10px auto;
    cursor: pointer;
  }

}

.entrance {
  position: absolute;
  right: 5px;
  top: 5px;

  .bg_img {
    width: 60px;
    height: 60px;
    background-image: url();
    background-size: 120px 120px;
    background-repeat: no-repeat;
    background-position: 0 0;
    cursor: pointer;

    &.pc {
      background-position: 0 -60px;
    }
  }

  .tips {
    position: absolute;
    top: 15px;
    right: 55px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 112px;
    height: 28px;
    background-color: #dff0d8;
    border-radius: 4px;
    text-align: center;

    .icon {
      &.scan {
        background-image: url();
        background-size: 14px;
      }

      &.safe {
        background-image: url();
      }
    }

    .text {
      margin-left: 4px;
      color: #20a53a;
    }
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #000000;
  font-family: Arial;
  font-size: 14px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

@media (max-width: 768px) {
  .el-login-footer {
    line-height: unset;
  }
}
</style>
